<template>
  <!-- 成品发货单 -->
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :btnList="btnList"
        :total="totalNum"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :minSearchLabelWidth="86"
        requestName="searchHandle"
        @add="addHandle"
        @print="printHandle"
        @delete="deleteHandle"
        @export="exportHandle"
        @rowView="rowViewHandle"
        @rowEdit="rowEditHandle"
      />
    </div>
    <!-- 新增 || 编辑 -->
    <TrLayout
      v-model="isShowAdd"
      :title="addEditTitle"
      :width="960"
      @close="addEditClose"
      @confrim="addEditConfrimHandle"
    >
      <template>
        <div class="table-edit-wrap">
          <div class="item-title">
            <div class="title-icon"></div>
            <div class="item-name">基础信息</div>
          </div>
          <TrEdit
            ref="trEdit"
            v-model="addEditForm"
            :formData="formData"
            :labelWidth="86"
            :list="addEditlist"
            :contentWidth="960"
            @select-change="selectChange"
            @clear="clearHandle"
          />
          <span class="ht-8"></span>
          <div class="item-title">
            <div class="title-icon"></div>
            <div class="item-name">出货信息</div>
          </div>
          <TrTable
            ref="addTrTable"
            isPopup
            isNeedSelection
            v-model="searchParamsAdd"
            :btnList="btnListAdd"
            :tableData="tableDataAdd"
            :tableColumn="tableColumnAdd"
            :minSearchLabelWidth="86"
            :slotStart="true"
            :isNeedPagination="false"
            @add="addDetailHandle"
            @delete="deleteDetailHandle"
            @input-back="inputBackHandleOut"
          >
            <template v-slot:sourceWarehouseId="{ row, prop }">
              <el-select
                v-model="row[prop]"
                filterable
                clearable
                placeholder="请选择"
                @visible-change="visibleChange($event, row, addEditType)"
              >
                <el-option
                  v-for="item in row.warehouseList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
          </TrTable>
        </div>
      </template>
    </TrLayout>
    <!-- 出货信息 -->
    <TrLayout
      v-model="isShowShipping"
      title="出货信息"
      :width="1227"
      :footerList="shippingFooterList"
      :footerTop="8"
      @close="shippingClose"
      @confrim="shippingConfrimHandle"
    >
      <template>
        <TrTable
          ref="shippingTrTable"
          isNeedSelection
          isPopup
          searchPaddingStyle="0 0 8px 0"
          v-model="searchParamsOut"
          :searchShowList="searchShowListOut"
          :total="totalNumOut"
          :tableData="tableDataOut"
          :tableColumn="tableColumnOut"
          :minSearchLabelWidth="86"
          requestName="searchHandleOut"
          @input-back="inputBackHandleOut"
        >
          <template v-slot:sourceWarehouseId="{ row, prop }">
            <el-select
              v-model="row[prop]"
              filterable
              clearable
              placeholder="请选择"
              @visible-change="visibleChange($event, row)"
            >
              <el-option
                v-for="item in row.warehouseList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </TrTable>
      </template>
    </TrLayout>
    <!-- 查看详情 -->
    <TrDetail
      v-model="isShowDetail"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
      :width="1227"
      :labelWidth="86"
      :isNeedFooter="false"
    >
      <template #table>
        <TrTable
          isPopup
          isNeedIndex
          :isNeedPagination="false"
          v-model="detailSearchParams"
          :tableData="detailTableData"
          :tableColumn="detailTableColumn"
          requestName="getBomListHandle"
          @rowView="rowDetailView"
        />
      </template>
    </TrDetail>

    <!-- 详情的详情 -->
    <TrDetail
      v-model="isShowDetailMat"
      :leftList="detailListMat"
      statusModel="hidden"
      :detailData="detailDataMat"
      :width="1227"
      :labelWidth="72"
      :isNeedFooter="false"
    >
      <template #tableMat>
        <TrTable
          isPopup
          isNeedIndex
          v-model="searchParamsMat"
          :tableData="tableDataMat"
          :expandObj="expandObj"
          :total="totalMat"
          rowKeyStr="barcodeId"
          :tableColumn="tableColumnMat"
          requestName="getMatListHandle"
        />
      </template>
    </TrDetail>

    <div class="print-wrap" v-if="isShowPrint">
      <logPrint
        ref="print"
        title="成品发货单"
        :printDataList="printDataList"
        :basicConfig="basicConfig"
        :tableHeaderConfig="printHeaderConfig"
        :signConfig="printSignConfig"
        :footerConfig="printFooterConfig"
      />
    </div>
  </div>
</template>

<script>
import {
  getList,
  getByCustomerAndState,
  save,
  getDetail,
  update,
  getBarcode,
  deleteAxios,
  getPrintData,
  delShipmentDetail,
  getWarehouseList,
} from "@/api/logistics/finishedShippingOrder.js";
import { cloneDeep } from "lodash-es";
import { getColor } from "@/utils/billColor";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
import logPrint from "./components/logPrint.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import TrEdit from "@/components/Tr-edit/Tr-edit.vue";
export default {
  name: "finishedShippingOrder",
  components: {
    TrTable,
    TrDetail,
    logPrint,
    TrLayout,
    TrEdit,
  },
  data: () => ({
    currentRow: {},
    isShowDetailMat: false,
    detailListMat: [
      {
        type: "text",
        id: 1,
        label: "基础信息",
        list: [
          {
            text: "成品料号",
            id: "materialCode",
            width: 33.33,
          },
          {
            text: "物料名称",
            id: "materialName",
            width: 33.33,
          },
          {
            text: "物料规格",
            id: "materialSpec",
            width: 33.33,
          },
          {
            text: "出库数量",
            id: "num",
            width: 33.33,
          },
          {
            text: "数量单位",
            id: "newNumUnit",
            width: 33.33,
          },
          {
            text: "出库重量",
            id: "weight",
            width: 33.33,
          },
          {
            text: "重量单位",
            id: "newWeightUnit",
            width: 33.33,
          },
        ],
      },
      {
        type: "slot",
        slotName: "tableMat",
        label: "标签明细",
        slotBottom: 32,
      },
    ],
    detailDataMat: {},
    searchParamsMat: {
      current: 1,
      size: 10,
    },
    tableDataMat: [],
    expandObj: {
      isNeedIndex: true,
      tableColumn: [
        {
          type: "text",
          label: "容器编码",
          value: "containerCode",
        },
        {
          type: "text",
          label: "数量",
          value: "num",
        },
        {
          type: "text",
          label: "数量单位",
          value: "newNumUnit",
        },
        {
          type: "text",
          label: "重量",
          value: "weight",
        },
        {
          type: "text",
          label: "重量单位",
          value: "newWeightUnit",
        },
      ],
      rowKeyStr: "containerId",
    },
    totalMat: 0,
    tableColumnMat: [
      {
        columnType: "expand",
        width: 60,
      },
      {
        type: "text",
        label: "包装标签",
        value: "barcode",
      },
      {
        type: "text",
        label: "包装规格",
        value: "packageSpec",
      },
      {
        type: "text",
        label: "合计包装数量",
        value: "numSum",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "合计包装重量",
        value: "weightSum",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "text",
        label: "托盘数量",
        value: "stockNum",
      },
      {
        type: "text",
        label: "包装人员",
        value: "packageUser",
      },
      {
        type: "text",
        label: "包装时间",
        value: "packageTime",
      },
    ],

    isShowDetail: false,
    detailData: {},
    detailList: [
      {
        type: "text",
        id: 1,
        label: "基础信息",
        list: [
          {
            text: "成品发货单",
            id: "billCode",
            width: 33.33,
          },
          {
            text: "客户名称",
            id: "customerName",
            width: 33.33,
          },
        ],
      },
      {
        type: "slot",
        slotName: "table",
        label: "出货信息",
        slotBottom: 32,
      },
    ],
    detailSearchParams: {
      current: 1,
      size: 10,
    },
    detailTableData: [],
    detailTableColumn: [
      {
        type: "text",
        label: "销售订单号",
        value: "saleOrderNo",
      },
      {
        type: "text",
        label: "销售订单行",
        value: "saleOrderLine",
      },
      {
        type: "text",
        label: "成品名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "成品料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "规格型号",
        value: "materialSpec",
      },
      {
        type: "text",
        label: "仓库",
        value: "sourceWarehouseName",
      },
      {
        type: "text",
        label: "数量",
        value: "num",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "text",
        label: "计划出货日期",
        value: "planDate",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
    ],

    searchParamsOut: {
      current: 1,
      size: 10,
    },
    totalNumOut: 0,
    searchShowListOut: [
      {
        label: "销售订单号",
        type: "input",
        width: 33.33,
        value: "",
        id: "saleOrderNo",
      },
      {
        id: "materialIdCode",
        type: "loadselect",
        width: 33.33,
        label: "成品料号",
        value: "",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          isEnabledList: [1],
          materialCodeType: 3,
        },
      },
      {
        id: "materialIdName",
        type: "loadselect",
        width: 33.33,
        label: "成品名称",
        value: "",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialName",
          rlLabel: "materialName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          isEnabledList: [1],
          materialCodeType: 3,
        },
      },
    ],
    isShowShipping: false,
    shippingFooterList: [
      {
        label: "取消",
        option: "close",
        color: "white",
      },
      {
        label: "保存",
        option: "confrim",
        color: "blue",
      },
    ],
    tableDataOut: [],
    tableColumnOut: [
      {
        type: "text",
        label: "销售订单号",
        value: "saleOrderNo",
      },
      {
        type: "text",
        label: "销售订单行",
        value: "saleOrderLine",
      },
      {
        type: "text",
        label: "成品名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "成品料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "规格型号",
        value: "materialSpec",
      },
      {
        type: "slot",
        slotName: "sourceWarehouseId",
        label: "仓库",
        value: "sourceWarehouseId",
      },
      {
        type: "text",
        label: "计划出货数量",
        value: "planShipmentNum",
      },
      {
        type: "text",
        label: "本次可出货数量",
        value: "usableNum",
      },
      {
        type: "input",
        label: "本次出货数量",
        value: "num",
        inputType: "number",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "本次出货重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },

      {
        type: "text",
        label: "计划出货日期",
        value: "planDate",
      },
      {
        type: "input",
        label: "备注",
        value: "remark",
      },
    ],

    addEditTitle: "新增",
    addEditType: "add",
    searchParamsAdd: {},
    btnListAdd: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "删除",
        option: "delete",
        color: "white",
        isRelaTable: true,
      },
    ],
    tableDataAdd: [],
    tableDataAddCopy: [],
    tableColumnAdd: [
      {
        type: "text",
        label: "销售订单号",
        value: "saleOrderNo",
      },
      {
        type: "text",
        label: "销售订单行",
        value: "saleOrderLine",
      },
      {
        type: "text",
        label: "成品名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "成品料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "规格型号",
        value: "materialSpec",
      },
      {
        type: "slot",
        slotName: "sourceWarehouseId",
        label: "仓库",
        value: "sourceWarehouseId",
      },
      {
        type: "text",
        label: "计划出货数量",
        value: "planShipmentNum",
      },
      {
        type: "text",
        label: "本次可出货数量",
        value: "usableNum",
      },
      {
        type: "input",
        label: "本次出货数量",
        value: "num",
        inputType: "number",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "本次出货重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "text",
        label: "计划出货日期",
        value: "planDate",
      },
      {
        type: "input",
        label: "备注",
        value: "remark",
      },
    ],

    isShowAdd: false,
    formData: {},
    addEditForm: {},
    addEditlist: [
      {
        id: "customerCode",
        type: "loadselect",
        width: 50,
        label: "客户名称",
        value: "",
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-warehouse-service/customer/page",
          method: "post",
          searchKey: "customerName",
          rlLabel: "customerName",
          rlValue: "customerCode",
          resultKey: "data,data,records",
        },
      },
    ],

    totalNum: 0,
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
      workOrderCode: "",
      materialCode: "",
      materialName: "",
      state: "",
    },
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    searchHideList: [
      {
        label: "成品发货单",
        type: "input",
        width: 33.33,
        value: "",
        id: "billCode",
      },
      {
        label: "客户名称",
        type: "input",
        width: 33.33,
        value: "",
        id: "customerName",
      },
      {
        label: "单据状态",
        type: "multiSelect",
        width: 33.33,
        value: "",
        list: [],
        id: "stateList",
      },

      {
        startStr: "updateTimeStart",
        endStr: "updateTimeEnd",
        id: "confirmTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        radio: -1,
        timePeriod: true,
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "打印",
        option: "print",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
      {
        label: "删除",
        option: "delete",
        color: "white",
        isRelaTable: true,
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "成品发货单",
        value: "billCode",
      },
      {
        type: "text",
        label: "客户名称",
        value: "customerName",
      },
      {
        type: "text",
        label: "单据状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "rowView",
          },
          {
            label: "编辑",
            option: "rowEdit",
          },
        ],
      },
    ],
    colorConfig: {
      10: "#ED7B2F", // 待备料
      20: "#2F7AED", // 备料中
      30: "#E34D59", // 待出库
      40: "#00A870", // 已出库
    },

    isShowPrint: false,
    basicConfig: [
      [
        { label: "单号", prop: "billCode" },
        { label: "出货日期", prop: "outboundDate" },
      ],
      [
        { label: "出货类型", prop: "outboundType" },
        { label: "客户名称", prop: "customerName" },
      ],
      [{ label: "销售业务员", prop: "salesperson" }],
    ],
    printHeaderConfig: [
      { label: "销售订单号", prop: "saleOrderNo" },
      { label: "成品料号", prop: "materialCode" },
      { label: "成品名称", prop: "materialName" },
      { label: "规格型号", prop: "materialSpec" },
      { label: "数量", prop: "num" },
      { label: "重量", prop: "weight" },
      { label: "备注", prop: "remark" },
    ],
    printSignConfig: [
      { label: "制单人", value: "", prop: "createUserName" },
      { label: "备料人", value: "", prop: "stoker" },
      { label: "审核人", value: "", prop: "auditor" },
      { label: "出库人", value: "" },
    ],
    printFooterConfig: { label: "表单编号", prop: "billCode" },
    printDataList: [],
  }),
  created() {
    // this.getListHandle();
    this.initHandle();
  },
  computed: {
    ids() {
      return this.$refs.trTable?.selectionList.map((item) => item.id);
    },
  },
  methods: {
    exportHandle() {
      this.$exportHandle({ vm: this, params: this.searchParams });
    },
    async visibleChange(event, row, type) {
      if (!event || type == "edit") return;
      const warehouseList = await this.getWarehouseList(row.materialId);
      this.$set(row, "warehouseList", warehouseList);
    },
    async getWarehouseList(materialId) {
      const { data: res } = await getWarehouseList({ materialId });
      return res.data.warehouseList.map((item) => {
        return {
          label: item.warehouseName,
          value: item.id,
        };
      });
    },
    clearHandle() {
      this.selectChange();
    },
    selectChange() {
      this.tableDataAdd = [];
    },
    async getDetailData(id) {
      const { data: res } = await getDetail({ id });
      return res.data;
    },
    shippingClose() {
      this.isShowShipping = false;
      this.tableDataOut = [];
      this.searchParamsOut = {
        size: 10,
        current: 1,
      };
      this.searchShowListOut.forEach((item) => {
        item.value = "";
        if (item.selectedLabel) item.selectedLabel = "";
      });
      this.$refs?.shippingTrTable?.clearSelect();
    },
    addEditClose() {
      this.isShowAdd = false;
      this.tableDataAdd = [];
      this.tableDataAddCopy = [];
      this.formData = {};
      this.shippingClose();
    },
    async saveHandle() {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认新增?`],
      });
      const shipmentInfoList = cloneDeep(this.tableDataAdd);
      this.$validateData(shipmentInfoList, 3);
      const axiosObj = {
        customerId: shipmentInfoList[0]?.customerId,
        shipmentInfoList,
      };
      await save(axiosObj);
      this.addEditClose();
      await this.getListHandle();
      this.$message.success(this.$t("msg.success"));
    },
    async editHandle() {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认编辑?`],
      });
      const updateCMDList = cloneDeep(this.tableDataAdd);
      this.$validateData(updateCMDList, 3);

      const delDetails = this.filterUniqueItems(
        this.tableDataAddCopy,
        updateCMDList,
        "bizDetailId"
      );
      if (delDetails.length !== 0) {
        const delAxios = {
          bizId: this.currentRow.id,
          bizDetailIds: delDetails.map((item) => item.bizDetailId),
        };
        await delShipmentDetail(delAxios);
      }

      const axiosObj = {
        id: this.currentRow.id,
        state: this.currentRow.state,
        updateCMDList,
      };
      await update(axiosObj);
      this.addEditClose();
      await this.getListHandle();
      this.$message.success(this.$t("msg.success"));
    },
    filterUniqueItems(list1, list2, key) {
      const list2Keys = new Set(list2.map((item) => item[key]));
      return list1.filter((item) => !list2Keys.has(item[key]));
    },
    searchHandleOut() {
      this.getByCustomerAndState();
    },
    async getByCustomerAndState() {
      const { data: res } = await getByCustomerAndState(this.searchParamsOut);
      this.$validateData(res.data.records);
      res.data.records.forEach((item) => {
        item.id = this.getId();
      });
      this.tableDataOut = res.data.records.map((item) => {
        return {
          ...item,
          newNumUnit: `${item.numUnitCode}(${item.numUnitName})`,
          newWeightUnit: `${item.weightUnitCode}(${item.weightUnitName})`,
          num: item.usableNum,
          warehouseList: [],
          sourceWarehouseId: "",
        };
      });

      this.totalNumOut = res.data.total;
    },
    async initHandle() {
      const res = await this.$fetchEnumApi("mes-warehouse-service", [
        "ProductOutBillStateEnum",
      ]);
      const list = res["ProductOutBillStateEnum"];
      const stateListObj = this.$findByProperty(
        this.searchHideList,
        "id",
        "stateList"
      );
      stateListObj && (stateListObj.list = list);
    },
    async getListHandle() {
      const { data: res } = await getList(this.searchParams);
      this.$validateData(res.data.records);
      res.data.records.forEach((item) => {
        item["stateNameColor"] = getColor("CPCK", item.state);
        item["isShowrowEdit"] = item.state !== 10;
      });
      this.tableData = res.data.records;
      this.totalNum = res.data.total;
    },
    searchHandle() {
      this.getListHandle();
    },
    inputBackHandleOut(headerObj, row) {
      if (headerObj.value !== "num") return;
      const numTo = this.isNoToNum([row]);
      if (!numTo) {
        row.weight = row.standardWeight * row.num;
      }
    },
    addHandle() {
      this.addEditTitle = "新增";
      this.addEditType = "add";
      this.isShowAdd = true;
    },
    async printHandle() {
      await this.getPrintData();
      this.isShowPrint = false;
      await this.$textShow({
        title: this.$t("tip.label"),
        content: ["是否确认打印？"],
      });
      this.isShowPrint = true;
      this.$nextTick(() => {
        this.$refs.print.printHandle();
        this.$refs.trTable.clearSelect();
      });
    },
    async getPrintData() {
      const { data: res } = await getPrintData({ ids: this.ids });

      this.printDataList = res.data.map((item) => {
        this.printSignConfig.forEach((i) => {
          if (!i.prop) return;
          i.value = item[i.prop];
        });
        return {
          ...item,
          qrCode: item.billCode,
          tableData: item.shipmentInfoList.map((i) => {
            return {
              ...i,
              num: `${i.num}${i.numUnitCode}`,
              weight: `${i.weight}${i.weightUnitCode}`,
            };
          }),
        };
      });

      this.$validateData(this.printDataList);
    },
    async deleteHandle() {
      const selectList = this.$refs.trTable.selectionList;
      const isNoOut = selectList.every((item) => item.state !== 40);
      if (!isNoOut)
        return this.$message.warning(
          "选择中存在【已出库】单据，【已出库】单据不可删除"
        );
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      });
      await deleteAxios({ ids: this.ids });
      this.$refs.trTable.clearSelect();
      this.getListHandle();
    },
    async rowViewHandle(row) {
      this.setDetailTableColumn(row);
      const res = await this.getDetailData(row.id);

      this.$validateData(res);
      this.detailData = res;
      this.detailTableData = res.shipmentInfoList;
      this.detailTableData.forEach((item) => {
        item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
        item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
      });

      this.isShowDetail = true;
    },
    setDetailTableColumn(row) {
      const option = {
        id: "optionID",
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [{ label: "查看", option: "rowView" }],
      };

      const viewColumn = [30, 40].includes(row.state);

      const findIdx = this.detailTableColumn.findIndex(
        (item) => item.id === "optionID"
      );

      if (viewColumn && findIdx === -1) {
        this.detailTableColumn.push(option);
      } else if (!viewColumn && findIdx !== -1) {
        this.detailTableColumn.splice(findIdx, 1);
      }
    },
    async rowEditHandle(row) {
      if (row.state !== 10)
        return this.$message.warning("仅【待备料】的单据允许编辑");

      this.addEditTitle = "编辑";
      this.addEditType = "edit";

      const res = await this.getDetailData(row.id);
      this.formData = res;
      this.currentRow = row;
      const customerCodeObj = this.$findByProperty(
        this.addEditlist,
        "id",
        "customerCode"
      );
      this.$validateData(res.shipmentInfoList);
      customerCodeObj && (customerCodeObj.selectedLabel = res.customerName);
      res.shipmentInfoList.forEach((item) => {
        item.id = this.getId();
      });

      res.shipmentInfoList.forEach((item) => {
        this.visibleChange(true, item);
      });

      this.tableDataAdd = res.shipmentInfoList;
      this.tableDataAdd.forEach((item) => {
        item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
        item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
      });
      this.tableDataAddCopy = cloneDeep(res.shipmentInfoList);

      this.isShowAdd = true;
    },
    getId() {
      const timestamp = Date.now();
      const randomNum = Math.floor(Math.random() * 10000);
      return `${timestamp}-${randomNum}`;
    },
    addEditConfrimHandle() {
      const flag = this.$refs.trEdit.validateHandle();
      if (!flag) return;
      if (this.tableDataAdd.length === 0)
        return this.$message.warning("请添加出货信息");
      if (this.isNoToNum(this.tableDataAdd)) return;
      if (this.isNoToWarehouse(this.tableDataAdd)) return;
      const fuc = {
        add: this.saveHandle,
        edit: this.editHandle,
      };
      fuc[this.addEditType]();
    },

    addDetailHandle() {
      const flag = this.$refs.trEdit.validateHandle();
      if (!flag) return;

      this.searchParamsOut.customerCode = this.addEditForm.customerCode;
      this.searchParamsOut.saleOrderListIds = this.tableDataAdd.map(
        (item) => item.saleOrderListId
      );

      this.getByCustomerAndState();
      this.isShowShipping = true;
    },
    async deleteDetailHandle() {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      });
      const selectList = this.$refs.addTrTable.selectionList;
      const ids = selectList.map((item) => item.id);

      this.tableDataAdd = this.tableDataAdd.filter(
        (item) => !ids.includes(item.id)
      );
      this.$refs.addTrTable.clearSelect();
    },

    shippingConfrimHandle() {
      const selectList = this.$refs.shippingTrTable.selectionList;
      if (selectList.length === 0)
        return this.$message.warning("请选择出货信息");

      if (this.isNoToNum(selectList)) return;
      if (this.isNoToWarehouse(selectList)) return;
      this.$validateData(selectList);

      this.tableDataAdd = [...this.tableDataAdd, ...selectList];
      this.$refs.shippingTrTable.clearSelect();
      this.isShowShipping = false;
    },
    isNoToNum(rows) {
      const rowsCopy = cloneDeep(rows);
      this.$validateData(rowsCopy, 3);
      return rowsCopy.some((item) => {
        if (item.num <= 0) {
          this.$message.warning(
            `销售订单号为${item.saleOrderNo}的本次出货数量不能小于或等于0`
          );
          return true;
        }
        if (this.addEditType != "edit" && item.num > item.usableNum) {
          this.$message.warning(
            `销售订单号为${item.saleOrderNo}的本次出货数量不能超过本次可出货数量：${item.usableNum}`
          );
          return true;
        }
        if (!Number.isInteger(Number(item.num))) {
          this.$message.warning(
            `销售订单号为${item.saleOrderNo}的本次出货数量只能输入整数`
          );
          return true;
        }
      });
    },
    isNoToWarehouse(rows) {
      const rowsCopy = cloneDeep(rows);
      this.$validateData(rowsCopy, 3);
      return rowsCopy.some((item) => {
        if (!item.sourceWarehouseId) {
          this.$message.warning(
            `销售订单号为${item.saleOrderNo}的仓库不能为空！`
          );
          return true;
        }
      });
    },
    async rowDetailView(row) {
      const axiosObj = {
        ...this.searchParamsMat,
        detailId: row.bizDetailId,
      };
      const { data: res } = await getBarcode(axiosObj);
      this.$validateData(res);
      this.detailDataMat = res.data;
      this.detailDataMat.newNumUnit = `${res.data.numUnitCode}(${res.data.numUnitName})`;
      this.detailDataMat.newWeightUnit = `${res.data.weightUnitCode}(${res.data.weightUnitName})`;
      this.setTableDataMat(res.data.pageParticularsResp);

      this.isShowDetailMat = true;
    },
    setTableDataMat(res) {
      this.tableDataMat = res.records.map((item) => {
        const expandChildren = item.labelContainerList.map((i) => {
          return {
            ...i,
            newNumUnit: `${item.numUnitCode}(${item.numUnitName})`,
            newWeightUnit: `${item.weightUnitCode}(${item.weightUnitName})`,
          };
        });
        const { numSum, weightSum } = this.getSum(expandChildren);
        return {
          ...item,
          numSum,
          weightSum,
          newNumUnit: `${item.numUnitCode}(${item.numUnitName})`,
          newWeightUnit: `${item.weightUnitCode}(${item.weightUnitName})`,
          packageSpec: expandChildren[0] ? expandChildren[0].packageSpec : "-",
          packageUser: expandChildren[0]
            ? expandChildren[0].createUserName
            : "-",
          packageTime: expandChildren[0] ? expandChildren[0].createTime : "-",
          expandChildren,
        };
      });

      this.totalMat = res.total;
    },
    getSum(list) {
      return list.reduce(
        (acc, item) => {
          const num =
            typeof item.num === "number" ? item.num : parseFloat(item.num);
          const weight =
            typeof item.weight === "number"
              ? item.weight
              : parseFloat(item.weight);

          if (!isNaN(num)) {
            acc.numSum += num;
          }
          if (!isNaN(weight)) {
            acc.weightSum += weight;
          }

          return acc;
        },
        { numSum: 0, weightSum: 0 }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.print-wrap {
  position: fixed;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -999;
  opacity: 0;
}
.table-edit-wrap {
  flex: 1;
  display: flex;
  flex-direction: column;
  .item-title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 16px;
    .title-icon {
      position: absolute;
      left: 0;
      top: 4px;
      width: 4px;
      height: 12px;
      border-radius: 4px;
      background: linear-gradient(
        180deg,
        rgba(107, 114, 255, 1) 0%,
        rgba(34, 39, 209, 1) 100%
      );
    }
    .item-name {
      color: rgba(#000, 0.9);
      font-weight: 600;
      font-size: 14px;
    }
  }
}
</style>
